/**
 * 
 */
package com.demo2do.strawberry.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.demo2do.core.persistence.GenericDaoSupport;
import com.demo2do.strawberry.dao.UserDao;
import com.demo2do.strawberry.entity.startup.Startup;
import com.demo2do.strawberry.entity.user.UserRegister;
import com.demo2do.strawberry.entity.user.member.Member;
import com.demo2do.strawberry.entity.user.member.MemberTask;
import com.demo2do.strawberry.entity.user.profile.Profile;
import com.demo2do.strawberry.service.UserService;

/**
 * @author Downpour
 */
@Service("userService")
public class UserServiceImpl implements UserService {
	
	@Autowired
	private GenericDaoSupport genericDaoSupport;
	
	@Autowired
	private UserDao userDao;
	
	/* (non-Javadoc)
	 * @see com.demo2do.strawberry.service.UserService#getUserRegister(java.lang.String, boolean)
	 */
	public List<UserRegister> getUserRegister(String email, boolean enabled) {
		return userDao.getUserRegister(email, enabled);
	}

	/* (non-Javadoc)
	 * @see com.demo2do.strawberry.service.UserService#getUserProfile(com.demo2do.strawberry.entity.user.Member)
	 */
	public Profile getUserProfile(Member member) {
		return userDao.getUserProfile(member);
	}

	/* (non-Javadoc)
	 * @see com.demo2do.strawberry.service.UserService#loadMemberTask(java.lang.Long)
	 */
	public MemberTask loadMemberTask(Long id) {
		return genericDaoSupport.load(MemberTask.class, id);
	}

	/* (non-Javadoc)
	 * @see com.demo2do.strawberry.service.UserService#editProfile(com.demo2do.strawberry.entity.user.UserRegister, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
	 */
	public void editProfile(UserRegister userRegister, String name, String description, String phone, String region) {

		Member member = userRegister.getMember();

		Profile profile = userDao.getUserProfile(member);

		// save or update profile
		genericDaoSupport.saveOrUpdate(profile.edit(name, description, phone, region));

		// update uesrRegister profile
		userRegister.setProfile(profile);

		// update member task
		MemberTask memberTask = genericDaoSupport.load(MemberTask.class, member.getId());
		memberTask.setProfileCompleted(true);
		genericDaoSupport.update(memberTask);
	}

	/* (non-Javadoc)
	 * @see com.demo2do.strawberry.service.UserService#isSubscribed(com.demo2do.strawberry.entity.user.profile.Profile, com.demo2do.strawberry.entity.startup.Startup)
	 */
	public boolean isSubscribed(Profile profile, Startup startup) {

		Map<String, Object> params = new HashMap<String, Object>();
		params.put("profile", profile);
		params.put("startup", startup);

		return !genericDaoSupport.searchForList("From Fans fan where fan.profile = :profile AND fan.startup = :startup", params).isEmpty();
	}

}
